package cn.wizzer.framework.util;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

public class ImageUtil {
    private static final Log log = Logs.get();
    public static String imageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(Objects.requireNonNull(data));
    }
    public static String imageToBase64(byte[] data){
        if (null == data)return "";
        return new BASE64Encoder().encode(data);
    }

    private static boolean reTry = true;
    public static void createFile(byte[] bytes, String path) {
        try {
            FileOutputStream outputStream = new FileOutputStream(new File(path));
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            reTry = true;
        } catch (IOException e) {
            String dir = path.substring(0, path.lastIndexOf("/"));
            try {
                Files.createDirectories(Paths.get(dir));
                if (reTry)createFile(bytes,path);
            } catch (IOException ex) {
                reTry = false;
                ex.printStackTrace();
            }
            log.error(e.getMessage());
        }
    }

    public static void removeFile(String path) {
        try {
            File file = new File(path);
            file.delete();
        }catch (Exception e){

        }
    }
}
